package Compresor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.BitSet;

public class Lector
{
    public Lector()
    {
        
    }

    public static void GuardaFichero(String nombre, String bits)
    {
        try
        {
            //System.out.println(bits.length() + ":" +bits.length()%8);
            
            FileOutputStream fos=new FileOutputStream(nombre);

            while((bits.length()-1)%7!=0)
            {
                bits+="0";
            }
            
            //System.out.println(bits.length()+ ":" +bits.length()%8);
            //System.out.println(bits);
            for(int i=0; i<bits.length()-1; i+=7)
            {
                byte x = Byte.parseByte(bits.substring(i,i+7), 2);
                /*
                String s = Integer.toBinaryString(x);
                while (s.length()%7 != 0)
                {
                    s="0"+s;
                }
                //System.out.print(s + " ");
                */
                fos.write(x);
            }
            //System.out.println();
            fos.close();
        }
        catch(FileNotFoundException ex)
        {
            System.out.println("Error, el fichero no existe.");
        }
        catch(IOException ex)
        {
            System.out.println("Error al leer el fichero.");
        }
    }
    
    public static String LeerFichero(String fichero)
    {
        StringBuilder conjunto=new StringBuilder();
        
        try
        {
            FileInputStream entrada = new FileInputStream(fichero);
            
            double i=0;
            double tam = entrada.available();
            while(entrada.available()!=0)
            {
                System.out.println(i/tam);
                int x = entrada.read();
                //System.out.print(x + " ");
                
                String s = Integer.toBinaryString(x);
                while (s.length()%7 != 0)
                {
                    s="0"+s;
                }
                conjunto.append(s);
                i++;
            }
            //System.out.println();

            entrada.close();
            

        }
        catch(FileNotFoundException ex)
        {
            System.out.println("Error, el fichero no existe.");
        }
        catch(IOException ex)
        {
            System.out.println("Error al leer el fichero.");
        }
        //System.out.println(conjunto);
        return conjunto.toString();
    }
}
